package com.witmed.user.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.witmed.lib_http.entity.UserEntity
import com.witmed.user.intent.UserIntent
import com.witmed.user.repos.RegisterRepository
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

sealed class LoginState {
    data class LoginSuccess(var user: UserEntity) : LoginState()
    data class Error(val msg: String) : LoginState()
    object Loading:LoginState()
}

class LoginViewModel:ViewModel() {
    val registerRepository by lazy{RegisterRepository()}
    //创建一个意图管道
    val loginChannel= Channel<UserIntent>(Channel.UNLIMITED)
    //可变状态的数据流
    private val _loginState= MutableStateFlow<LoginState>(LoginState.Loading)
    //可观察的数据流
    val loginState: StateFlow<LoginState>
        get() = _loginState

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            loginChannel.consumeAsFlow().collect{
                when(it){
                    is UserIntent.login->{
                        login(it.username,it.password)
                    }
                    else->{}
                }
            }
        }
    }

    fun login(name:String,pass:String){
        viewModelScope.launch {
            val resp = registerRepository.login(name, pass)
            if(resp.code==0){
                _loginState.value=LoginState.LoginSuccess(resp.data!!)
            }else{
                _loginState.value=LoginState.Error(resp.msg)
            }
        }

    }
}